package cn.lupin.utils;

import com.jcraft.jsch.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SftpUtils {

    private static final Logger log = LoggerFactory.getLogger(SftpUtils.class);
    private static final String USER_NAME = "root";
    private static final String PASSWORD = "root";
    private static final String HOST = "192.168.42.130";
    private static final Integer PORT = 22;

    public static void downFile(String localFilePath, String remoteFilePath) {

        ChannelSftp sftp = null;
        Session session = null;
        try {
            // 1. 建立连接
            JSch jsch = new JSch();
            session = jsch.getSession(USER_NAME, HOST, PORT);
            session.setPassword(PASSWORD);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();
            sftp = (ChannelSftp) session.openChannel("sftp");
            sftp.connect();
            // 2. 下载文件
            sftp.get(remoteFilePath, localFilePath);
            log.info("文件下载成功，localFilePath:{}", localFilePath);
        } catch (JSchException | SftpException e) {
            e.printStackTrace();
        } finally {
            // 3. 关闭连接
            if (sftp != null) {
                sftp.exit();
            }
            if (session != null) {
                session.disconnect();
            }
        }
    }
}
